<template>
  <BasicDrawer @register="register" :title="title">
    <a-form :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-item label="name" v-bind="validateInfos.username">
        <a-input v-model:value="modelRef.username" placeholder="input name" />
      </a-form-item>
      <a-form-item label="password" v-bind="validateInfos.password">
        <a-input-password
          v-model:value="modelRef.password"
          placeholder="input password"
        />
      </a-form-item>
      <a-form-item label="phone" v-bind="validateInfos.phone">
        <a-input
          v-model:value="modelRef.phone"
          placeholder="input phone"
          @pressEnter="handleSubmit"
        />
      </a-form-item>
    </a-form>
    <div style="position: absolute; bottom: 20px; right: 20px; width: 100%">
      <a-divider />
      <div style="float: right">
        <a-button type="primary" @click="cancel" style="margin-right: 20px"
          >cancel</a-button
        >
        <a-button type="primary" @click="handleSubmit">submit</a-button>
      </div>
    </div>
  </BasicDrawer>
</template>
<script lang="ts">
import { defineComponent, ref, toRaw, unref } from "vue";
import { Form } from "ant-design-vue";
import { BasicDrawer, useDrawerInner } from "/@/components";
import { modelRef, rulesRef } from "./index.data";
import { Api } from "/@/api";
export default defineComponent({
  components: { BasicDrawer },
  emits: ["success",'register'],
  setup(_, { emit }) {
    const contant = ref();
    const title = ref();
    const isEdit = ref();
    const editId = ref();
    const useForm = Form.useForm;
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );
    const [register, closeDrawer] = useDrawerInner(async (c: any) => {
      resetFields();
      contant.value = c;
      isEdit.value = c.isEdit;
      if (c.isEdit) {
        title.value = "编辑 - " + c.username;
        modelRef.username = c.username;
        modelRef.phone = c.phone;
        modelRef.password = c.password;
        editId.value = c.id;
      } else {
        title.value = "新建";
      }
    });
    function cancel() {
      closeDrawer();
    }
    function handleSubmit() {
      validate().then(() => {
        if (unref(isEdit)) {
          Api.user
            .updateUser({ ...toRaw(modelRef), id: editId.value })
            .then(() => {
              closeDrawer();
              emit("success");
            });
        } else {
          Api.user.addUser(toRaw(modelRef)).then(() => {
            closeDrawer();
            emit("success");
          });
        }
      });
    }

    return {
      register,
      cancel,
      handleSubmit,
      contant,
      title,
      validateInfos,
      resetFields,
      modelRef,
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
    };
  },
});
</script>
